/**
 * @author prateekpatil
 * @author kevingomes
 */
import java.io.*;

public class Peer extends Thread {
    //Creating Client object
    private Client clientObj;
    
    private Server serverObj;

    private Boolean peersConnectedFlag = false;

    //Constructor
    public Peer(String clientName) {
	this.clientObj = new Client();
	this.serverObj = new Server();

	this.clientObj.init(clientName, serverObj);
	this.serverObj.init(clientObj);
    }
    
    public static void main (String args[]) {
	
	if(args.length != 1) {
	    System.out.println("Syntax: Peer <client_name>");
	    System.exit(1);
	}

	Peer obj = new Peer(args[0]);
   
	try {   
	    for (;;) {    
                Integer inputValue = new Integer(obj.displayFileMenu());
                obj.checkOption("Menu", inputValue);    
            }
        } catch(IOException e) {
	    System.err.print("Error in infinite for loop");
	}
    }

    public Integer displayFileMenu() {
	//System.out.println("1 - View My Files");
	System.out.println("2 - Search File");
        //System.out.println("3 - List of neighbours");
	System.out.println("0 - Exit"); System.out.println();
	System.out.print("Enter Choice: ");

	int value = 0;
        try {
            InputStreamReader inputStream = new InputStreamReader(System.in);
            BufferedReader userInput = new BufferedReader(inputStream);
            String line = userInput.readLine();

	    System.out.println("Entered: "+line);
	    Integer choice = new Integer(line);	
	    System.out.println("Choice: "+choice);
	    value = choice.intValue();

	} catch(IOException e) {
	    System.out.println("Read input exception: "+e);
	}

	return value;
    }

    public void checkOption(String menu, Integer value) throws IOException {
	System.out.println("Selected option: "+value);
	if(menu.equals("Menu")) {
	    switch(value) {
	    case 2:
		if(this.peersConnectedFlag == false) {
		    //Establishing the connection with all neighbors
		    this.clientObj.connectNeighbors();
		    this.peersConnectedFlag = true;
		}

		System.out.println("Please enter filename to search: ");
               	try {
		    BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
                    String fileName = read.readLine();
		    this.clientObj.searchNeighbor(fileName);
                    read.close();
		} catch(Exception e) {
		    System.out.println("Read input exception: "+e);
		}
		break;
	    case 0:
                //Closing the Connection to neighbors 
                this.clientObj.closeConnections();
                System.exit(0);
	    default:
		System.out.println ("Invalid option! Try again.");
		break;
	    }	
	}
    }
}
